<?php
// 应用公共文件
use think\facade\Db;
use think\facade\Request;
use app\model\Config;
use app\model\User;
use app\model\UserQywx;
use app\model\Recharge;
use app\model\OpAccount;
use app\model\AccInfo;
use app\model\Items;
use app\model\ItemConsume;
/**
 * GET 请求
 * @param string $url
 */
function http_get($url,$headers=false) {  
	$oCurl = curl_init();
	if (stripos($url, "https://") !== FALSE) {
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
	}
	curl_setopt($oCurl, CURLOPT_URL, $url);
	curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
	if($headers){
	    curl_setopt($oCurl, CURLOPT_HEADER, 0);
	    curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
	}else{
	    curl_setopt($oCurl, CURLOPT_HEADER, 1);
	}

	// $sContent = curl_exec($oCurl);
	// $aStatus = curl_getinfo($oCurl);
	//$sContent = execCURL($oCurl);
    $sContent = curl_exec($oCurl);
	curl_close($oCurl);

	return $sContent;
}
function http_gett($url,$headers=false) {  
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
    if($headers){
        curl_setopt($oCurl, CURLOPT_HEADER, 0);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
    }else{
        curl_setopt($oCurl, CURLOPT_HEADER, 1);
    }

    // $sContent = curl_exec($oCurl);
    // $aStatus = curl_getinfo($oCurl);
    $sContent = execCURL($oCurl);
    curl_close($oCurl);

    return $sContent;
}
/**
 * POST 请求
 * @param string $url
 * @param array $param
 * @param boolean $post_file 是否文件上传
 * @return string content
 */
function http_post($url,$param,$post_file=false,$headers=false) {
    $oCurl = curl_init();

    if (stripos($url,"https://")!==FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
        $is_curlFile = true;
    } else {
        $is_curlFile = false;
        if (defined('CURLOPT_SAFE_UPLOAD')) {
            curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
        }
    }
    
    if ($post_file) {
        if ($is_curlFile) {
            foreach ($param as $key => $val) {                     
                if (isset($val["tmp_name"])) {
                    $param[$key] = new \CURLFile(realpath($val["tmp_name"]),$val["type"],$val["name"]);
                } else if (substr($val, 0, 1) == '@') {
                    $param[$key] = new \CURLFile(realpath(substr($val,1)));                
                }                           
            }
        }                
        $strPOST = $param;
    } else {
        $strPOST = json_encode($param);
    } 
    
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($oCurl, CURLOPT_POST, true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
    curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
    if($headers){
        curl_setopt($oCurl, CURLOPT_HEADER, 0);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
    }else{
        curl_setopt($oCurl, CURLOPT_HEADER, 1);
    }
    
    // $sContent = curl_exec($oCurl);
    // $aStatus  = curl_getinfo($oCurl);

    // $sContent = execCURL($oCurl);
    $sContent = curl_exec($oCurl);
    curl_close($oCurl);

    return $sContent;
}

/**
 * 执行CURL请求，并封装返回对象
 */
function execCURL($ch) {
	$response = curl_exec($ch);
	$error    = curl_error($ch);
	$result   = array( 'header' => '', 
		'content' => '', 
		'curl_error' => '', 
		'http_code' => '',
		'last_url' => '');
	
	if ($error != "") {
		$result['curl_error'] = $error;
		return $result;
	}

	$header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
	$result['header'] = str_replace(array("\r\n", "\r", "\n"), "<br/>", substr($response, 0, $header_size));
	$result['content'] = substr( $response, $header_size );
	$result['http_code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	$result['last_url'] = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
	$result["base_resp"] = array();
	$result["base_resp"]["ret"] = $result['http_code'] == 200 ? 0 : $result['http_code'];
	$result["base_resp"]["err_msg"] = $result['http_code'] == 200 ? "ok" : $result["curl_error"];

	return $result;
}

//添加操作记录
function log_add($type,$remark=''){
    $request = Request::instance();
    $arr["site"] = $request->controller().'/'.$request->action();
    $arr["ip"] = $request->ip();
    $arr["uid"] = session("uid");
    $arr["role_id"] = session("info.role_id");
    $arr["create_time"] = time();
    $arr["type"] = $type;
    $arr["remark"] = $remark;
    Db::name("logs")->save($arr); 
}

// 据IP获得地址
function location($ip='') {
	$ip = empty($ip) ? request()->ip() : $ip;
	$api_url = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=".$ip;
	$res = file_get_contents($api_url);
	$result = iconv("GBK", "UTF-8", $res);
	$info = json_decode($result, 1);
	return $info;
}

//生成随机编号
function get_numbers($str){
    $d = date("Ymd",time()).rand(10000,99999);
    return $str.$d;
}
//账号币兑换人民币
function zhb_cny($zhb,$ratio){
    
    if($ratio >= 0){
        $c = $zhb/(1+$ratio/100);
        $cny = round($c,2);
    }else{
        $ratio = abs($ratio);
        $c = $zhb*(1+$ratio/100);
        $cny = round($c,2);
    }
    return $cny;
}
//人民币兑换账号币
function cny_zhb($cny,$ratio,$type=1){
    
    if($ratio >= 0){
        $c = $cny*(1+$ratio/100);
        $zhb = round($c,2);
    }else{
        $ratio = abs($ratio);
        $c = $cny/(1+$ratio/100);
        $zhb = round($c,2);
    }
    return $zhb;
}
//账户币充值 计算 人民币利润
function cny_profit($zhb,$ratio,$qd_ratio){
    
    if($ratio >= 0){
        $l1 = $zhb/(1+$ratio/100);
        $l2 = $zhb/(1+$qd_ratio/100);
        $l = $l1 - $l2;
    }else{
        $ratio = abs($ratio);
        $l1 = $zhb*(1+$ratio/100);
        $l2 = $zhb/(1+$qd_ratio/100);
        $l = $l1 - $l2;
    }
    
    return $l = round($l,2);
}
//A量 加粉 账户币充值 计算 人民币利润
/* 
 * $cost 成本    $num 数量    $sell 销售价
 *  */
function fans_cny_profit($num,$sell,$cost){
    $l1 = $num*$sell;
    $l2 = $num*$cost;
    $l = $l1 - $l2;
    return $l = round($l,2);
}
// 获取/更新 access_token
function qywx_token() {
    $qywx_conf = config('qywx');
    $qywx_token = Config::where(['group'=>'qywx', 'key'=>'access_token'])->find();
    $expire_time = empty($qywx_token) ? 0 : intval($qywx_token->update_time) + intval($qywx_conf['expire_time']);
    $qywx_token = empty($qywx_token) 
        ? Config::create(['group'=>'qywx', 'key'=>'access_token']) 
        : $qywx_token;
    if ($expire_time < time()) { 
        $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$qywx_conf['corp_id']}&corpsecret={$qywx_conf['secret']}";
        $res = json_decode(http_gett($url)["content"]);
        $res->access_token;
        if ($res->access_token) {
            $qywx_token->value = $res->access_token;
            $qywx_token->save();
        }
    }
    return $qywx_token->value;
}
//编辑发送消息
/* 1:发送出纳  客户打款  2:发送出纳 账户充值  5发送出纳 客户退款  6发送出纳 账户退款  
 * 3：发送媒介 客户打款成功  
 * 4：发送媒介和运营 账户充值成功 7：发送媒介和运营 客户退款成功 8：发送媒介和运营 账户退款成功
 *  */
function get_msg_info($type,$u,$name=0,$money=0){
    $t = date('Y-m-d H:i:s',time());
    if(!empty($type) && !empty($name) && !empty($money)){
        if($type == 1){ //只发给财务出纳 打款
            //发给出纳打款
            $msg = "***您有新的消息*** \n 类型：`客户打款` \n 客户：<font color=\"info\">$name</font>  \n 金额：<font color=\"comment\">$money</font>  \n 时间：$t \n 请您尽快处理。 \n"; 
        }elseif ($type == 2){ //只发给财务出纳 充值
            //发给出纳充值
            $msg = "***您有新的消息*** \n 类型：`账户充值` \n 账户ID：<font color=\"info\">$name</font>  \n 账户币：<font color=\"comment\">$money</font>  \n 时间：$t \n 请您尽快处理。 \n"; 
        }elseif ($type == 3){
            //发送媒介 打款成功
            $msg = "***您有新的消息*** \n 类型：`打款成功` \n 客户：<font color=\"info\">$name</font>  \n 金额：<font color=\"comment\">$money</font>  \n 时间：$t \n ";  
        }elseif ($type == 5){
            //发送媒介 打款成功
            $msg = "***您有新的消息*** \n 类型：`客户退款` \n 时间：$t \n >请您尽快处理。 \n";  
        }elseif ($type == 6){
            //发送媒介 打款成功
            $msg = "***您有新的消息*** \n 类型：`账户退款` \n 时间：$t \n >请您尽快处理。 \n";  
        }elseif ($type == 4){
            //发送媒介 打款成功
            $msg = "***您有新的消息*** \n 类型：`充值成功` \n 账户ID：<font color=\"info\">$name</font>  \n 账户币：<font color=\"comment\">$money</font>  \n 时间：$t ";  
        }
        
        qywx_send($u, $msg);
    }
    
}
//编辑发送消息
/*1打款驳回  3退款驳回，2账户充值驳回，4账户退款驳回  */
function get_msg_bh_info($type,$u,$name,$money){
    $t = date('Y-m-d H:i:s',time());
    //打款驳回
   if(!empty($type) && !empty($name) && !empty($money)){
        if($type == 1){ //只发给媒介 打款驳回
            $msg = "***您有新的消息*** \n 类型：`客户打款驳回` \n 客户：<font color=\"info\">$name</font>  \n 金额：<font color=\"comment\">$money</font>  \n 时间：$t \n 请您尽快处理。 \n";
        }elseif ($type == 2){ //只发给媒介  账户充值驳回
            $msg = "***您有新的消息*** \n 类型：`账户充值驳回` \n 账户ID：<font color=\"info\">$name</font>  \n 账户币：<font color=\"comment\">$money</font>  \n 时间：$t \n 请您尽快处理。 \n";
        }elseif ($type == 3){//只发给媒介 客户退款驳回
            $msg = "***您有新的消息*** \n 类型：`客户退款驳回` \n 客户：<font color=\"info\">$name</font>  \n 金额：<font color=\"comment\">$money</font>  \n 时间：$t \n 请您尽快处理。 \n";
        }elseif ($type == 4){//只发给媒介 账户充值驳回
            $msg = "***您有新的消息*** \n 类型：`账户退款驳回` \n 账户币：<font color=\"comment\">$money</font>  \n 时间：$t \n 请您尽快处理。 \n";
        }elseif ($type == 5){//只发给媒介 账户充值驳回
            $msg = "***您有新的消息*** \n 类型：`账户绑定成功` \n 账户ID：<font color=\"comment\">$money</font>  \n 时间：$t \n 请您尽快处理。 \n";
        }
        qywx_send($u, $msg);
    }
}
//$uid:  "1,2,3"
function qywx_send($uid=0, $data='') {
    $conf = config('qywx');
    $token = qywx_token();
    if ($uid == '@all') {
        $user = '@all';
    } else {
        $w[] = ['id','in',$uid.','];
        $u = User::where($w)->column('qywx_id');
        if(empty($u)){
            return false;
        }
        $w1[] = ['id','in',$u];
        $userid = UserQywx::where($w1)->column('userid');
        if(empty($userid)){
            return false;
        }
        $user = implode('|', $userid);
        
    }
   
    $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token}";
    $data = [
        'touser' => $user,
        // 'toparty' => '4',
        'msgtype' => 'markdown',
        'agentid' => $conf['agent_id'],
        'markdown' => [
            'content' => $data,
        ],
    ];
    $res = http_post($url, $data);
    return $res;
}
//C方法
function C($k,$v=null){
    if($v != null){
        $r = Config::where('key',$k)->update(['value'=>$v]);
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        $r = Config::where('key',$k)->value('value');
        if($r){
            return $r;
        }else{
            return false;
        }
    }
}
 //获取最后5次充值的所有返点，先冲先消耗，计算消耗利润
/*
$item_id  项目id   $op_account_id 账户id  $currency  消耗账户币

*/
 function get_xh_rebates($item_id,$op_account_id,$currency){
    $wh['status'] = 1;
    $wh['type'] = 2;
    $wh['items_id'] = $item_id;
    $list = Recharge::field('rebate,service_pay,channel_rebate,currency,is_fans')->where($wh)->order('update_time desc')->limit('5')->select()->toArray();
    $yue = OpAccount::field('balance')->where('id',$op_account_id)->find();
    $arr = get_next_info($list, $yue['balance']);
    if(empty($arr)){
        return 0;
    }
    if($arr['k'] == 0){
        $profit = get_profit($list[0],$currency);
    }else{
        $profit = 0;
        $y = $currency - $arr['y'];
        for ($i=$arr['k'];$i>=0;$i--){
            
            if($i == $arr['k']&& $y <= 0){
               
                $profit = $this->get_profit($list[$i],$currency);
                break;
            }elseif ($i == $arr['k']&& $y > 0){
               
                $profit += $this->get_profit($list[$i],$arr['y']);
            }else{
               
                if($y <= $list[$i]['currency']){
                  
                    if($y == $list[$i]['currency']){
                        $y = $list[$i]['currency'];
                    }
                    $profit += $this->get_profit($list[$i],$y);
                    break;
                }else{
                    
                    $y = $y - $list[$i]['currency'];
                    $profit += $this->get_profit($list[$i],$list[$i]['currency']);
                }
            }
        }    
    }
    
    return $profit;
}
//获取利润
function get_profit($r,$currency){
    return $profit = cny_profit($currency, $r['rebate'], $r['channel_rebate']);    
}
//获取下一级
function get_next_info($list,$yue){
    $y = $yue; 
    for ($k=0;$k<count($list);$k++){
        $y = $y - $list[$k]['currency'];
        if($y <= 0){
            $y = $y==0?0:-$y;
            $arr['k'] = $k;
            $arr['y'] = $y;
            return $arr;
        }
    }
     
}

//账号完成率			
	// 评定完成率标准：				
	// 1.   开户中 ==============================================2%				
	// 2.   素材已准备完毕等待上传====================================5%				
	// 3   审核页与投放页面已准备完毕  =================================8%				
	// 4.   账户创建成功搭建第一阶段素材================================5%				
	// 5.   账户第一阶段素材已通过搭建第二阶段投放素材=======================10%				
	// 6.   第二阶段投放素材已通过等待投放===============================30%				
	// 7.   明确客户KPI需求；账户开始投放===============================5%				
	// 8.   账户投放达到客户要求=====================================15%				
	// 9.   账户投放续费5次以上 =====================================10%				
	// 10. 账户续费10次以上 =======================================10%				
    //type == 1:账户进度，2账户的审核页与投放页是否准备完毕，3：账户是否投放
    function acc_lv($id,$type){
        if($type == 1){
            //账号进度
            $jindu = OpAccount::where('id',$id)->value('jindu');
            $lv = 0;
            switch ($jindu) {
                case '1': //开户中
                    $lv = 2;
                    break;
                case '6': //素材已准备完毕
                    $lv = 7;
                    break;
                case '2': //素材已准备完毕
                    $lv = 22;
                    break;
                case '3':   //第一阶段素材已通
                    $lv = 12;
                    break;
                case '4':   //第二阶段投放素材已通
                    $lv = 22;
                    break;
                case '5':
                    $lv = 52;
                    break;
                
                default:
                    break;
            }
        }elseif($type == 2){
            //账号审核页与投放页
            $putin = AccInfo::field("putin_url,consume_goal,form_goal")->where('pid',$id)->find();
            //审核页与投放页面已准备完毕
            if($putin['putin_url']){
                $lv = 60;
            }
        }elseif($type == 3){
            //账号是否投放
            $wh[] = ['op_account_id','=',$id];
            $wh[] = ['is_deliver','=',1];
            $wh[] = ['is_finish','=',0];
            $wh[] = ['status','=',1];
            $items = Items::where($wh)->find();
            //已投放
            if($items['id']){
                $lv = 65;
            }
        }
        
       

        

        
        
        return $lv;
    }